<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="书名"
        style="width: 200px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.author"
        placeholder="作者"
        style="width: 200px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <!-- 复选框区域 -->
      <el-select
        v-model="listQuery.category"
        placeholder="分类"
        clearable
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in categoryList"
          :key="item.value"
          :label="item.label + '(' + item.num + ')'"
          :value="item.label"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        style="margin-left: 10px"
        icon="el-icon-search"
        @click="handleFilter"
      >查询</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        style="margin-left: 5px"
        @click="handleCreate"
      >新增</el-button>
      <el-checkbox
        v-model="showCover"
        class="filter-item"
        style="margin-left: 5px"
        @change="changeShowCover"
      >
        显示封面
      </el-checkbox>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :default-sort="defaultSort"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      />
      <!-- 书名列 -->
      <el-table-column
        label="书名"
        width="150"
        align="center"
      >
        <template slot-scope="{ row: { titleWrapper }}">
          <span v-html="titleWrapper" />
        </template>
      </el-table-column>
      <!-- 作者列 -->
      <el-table-column
        label="作者"
        width="150"
        align="center"
      >
        <template slot-scope="{ row: { authorWrapper }}">
          <span v-html="authorWrapper" />
        </template>
      </el-table-column>
      <!-- 出版社列 -->
      <el-table-column label="出版社" prop="publisher" width="150" align="center" />
      <!-- 分类列 -->
      <el-table-column label="分类" prop="categoryText" width="100" align="center" />
      <!-- 语言列 -->
      <el-table-column label="语言" prop="language" align="center" />
      <!-- 封面列 -->
      <el-table-column
        v-if="showCover"
        label="封面"
        width="150"
        align="center"
      >
        <template slot-scope="{ row: { cover }}">
          <a :href="cover" target="_blank">
            <img :src="cover" style="width: 120px;height: 180px">
          </a>
        </template>
      </el-table-column>
      <!-- 文件名列 -->
      <el-table-column label="文件名" prop="fileName" width="100" align="center" />
      <!-- 文件路径列 -->
      <el-table-column label="文件路径" prop="filePath" width="100" align="center">
        <template slot-scope="{ row: { filePath }}">
          <span>{{ filePath | valueFilter }}</span>
        </template>
      </el-table-column>
      <!-- 封面路径列 -->
      <el-table-column label="封面路径" prop="coverPath" width="100" align="center">
        <template slot-scope="{ row: { coverPath }}">
          <span>{{ coverPath | valueFilter }}</span>
        </template>
      </el-table-column>
      <!-- 解压路径列 -->
      <el-table-column label="解压路径" prop="unzipPath" width="100" align="center">
        <template slot-scope="{ row: { unzipPath }}">
          <span>{{ unzipPath | valueFilter }}</span>
        </template>
      </el-table-column>
      <!-- 上传人列 -->
      <el-table-column label="上传人" prop="createUser" width="100" align="center">
        <template slot-scope="{ row: { createUser }}">
          <span>{{ createUser | valueFilter }}</span>
        </template>
      </el-table-column>
      <!-- 上传时间列 -->
      <el-table-column label="上传时间" prop="createDt" width="100" align="center">
        <template slot-scope="{ row: { createDt }}">
          <span>{{ createDt | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="120"
        align="center"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(row)" />
          <el-button type="text" icon="el-icon-delete" style="color: #f56c6c" @click="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import Pagination from '../../components/Pagination/index.vue'
// 水波效果
import waves from '../../directive/waves/waves'
import { getCategory, listBook, deleteBook } from '../../api/book'
import { parseTime } from '@/utils'

export default {
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    // 过滤器过滤不存在的数据并显示无
    valueFilter(value) {
      return value || '无'
    },
    // 过滤并格式化时间
    timeFilter(time) {
      return time ? parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}') : '无'
    }
  },
  data() {
    return {
      tableKey: 0,
      listLoading: true,
      listQuery: {},
      showCover: false,
      categoryList: [],
      list: [],
      total: 0,
      defaultSort: {}
    }
  },
  created() {
    this.parseQuery()
  },
  mounted() {
    this.getList()
    this.getCategoryList()
  },
  // 路由钩子监听路由的变化
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      // 浅拷贝出新路由
      const newQuery = Object.assign({}, to.query)
      // 浅拷贝出旧路由
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        // 刷新页面
        this.getList()
      }
    }
    next()
  },
  // props: {
  // 	total: {
  // 		required: true,
  // 	}
  // },
  methods: {
    parseQuery() {
      // 获取动态路由的参数值
      const query = Object.assign({}, this.$route.query)
      // 默认升序排列
      let sort = '+id'
      const listQuery = {
        page: 1,
        pageSize: 20,
        sort
      }
      if (query) {
        // 将page与pageSize属性转换成Number型
        if (query) {
          query.page && (query.page = +query.page)
          query.pageSize && (query.pageSize = +query.pageSize)
          // 更新排序方式
          query.sort && (sort = query.sort)
        }
        // 页面刷新后，获取sort是属性
        const sortSymbol = sort[0]
        const sortColumn = sort.slice(1, sort.length)
        console.log(sortSymbol, sortColumn)
        this.defaultSort = {
          prop: sortColumn,
          order: sortSymbol === '+' ? 'ascending' : 'descending'
        }
      }
      // 合并分页参数
      this.listQuery = { ...listQuery, ...query }
    },
    // 排序方法
    sortChange(data) {
      // console.log('sortChange', data)
      const { prop, order } = data
      this.sortBy(prop, order)
    },
    sortBy(prop, order) {
      if (order === 'ascending') {
        // 升序排列
        this.listQuery.sort = `+${prop}`
      } else {
        // 降序排列
        this.listQuery.sort = `-${prop}`
      }
      // 刷新页面
      this.handleFilter()
    },
    // 定义关键字高亮方法
    wrappperKeywork(k, v) {
      function highlight(value) {
        return `<span style="color: #1890ff">${value}</span>`
      }
      if (!this.listQuery[k]) {
        return v
      } else {
        // 定义正则表达式 => 全局的匹配关键字
        return v.replace(new RegExp(this.listQuery[k], 'ig'), v => highlight(v))
      }
    },
    getList() {
      this.listLoading = true
      listBook(this.listQuery).then(response => {
        const { list, count } = response.data
        this.list = list
        // 获取分页数据
        this.total = count
        // 暂停加载动画
        this.listLoading = false
        this.list.forEach(book => {
          book.titleWrapper = this.wrappperKeywork('title', book.title)
          book.authorWrapper = this.wrappperKeywork('author', book.author)
        })
      })
    },
    getCategoryList() {
      getCategory().then(response => {
        this.categoryList = response.data
        console.log(this.categoryList)
      })
    },
    refresh() {
      // 刷新页面的url
      this.$router.push({
        path: '/book/list',
        query: this.listQuery
      })
    },
    handleFilter() {
      console.log('handleFilter', this.listQuery)
      // 重置页码为1
      this.listQuery.page = 1
      // this.getList()
      this.refresh()
    },
    handleCreate() {
      // 跳转到上传电子书页
      this.$router.push('/book/create')
    },
    changeShowCover(value) {
      this.showCover = value
    },
    handleUpdate(row) {
      console.log('handleUpdate', row)
      // 跳转到编辑页面
      this.$router.push(`/book/edit/${row.fileName}`)
    },
    // 删除书本
    handleDelete(row) {
      // 显示提示信息
      this.$confirm('此操作将永久删除该电子书，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBook(row.fileName).then(response => {
          // 显示提示
          this.$notify({
            title: '成功',
            message: response.msg || '删除成功',
            type: 'success',
            duration: 2000
          })
          // 刷新列表
          this.handleFilter()
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
